package com.qidian.mes.sso.controller;

import com.qidian.mes.pojo.SysUser;
import com.qidian.mes.sso.service.SysUserService;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Time 2023/11/2 9:32
 * @Description
 */
@RestController
@RequestMapping("/sysUser")
@CrossOrigin
public class SysUserController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    public MESResult login(@RequestBody SysUser user){
        return userService.login(user);
    }

    @GetMapping("/checkLogin")
    public MESResult checkLogin(){
        // 不需要写任何业务，只要请求能够到达这里，说明肯定是登陆状态。
        return MESResult.ok();
    }

    @GetMapping("/getCode")
    // codeTag就是当前这个验证码的标记
    public void getCode(String codeTag,HttpServletResponse response) throws IOException {
        // 生成图片
        // 准备图片缓冲区
        BufferedImage bufferedImage = new BufferedImage(100,25,BufferedImage.TYPE_INT_RGB);
        // 通过缓冲区获取一支画笔
        Graphics gh = bufferedImage.getGraphics();
        // 填充背景色
        gh.setColor(Color.WHITE);
        gh.fillRect(0,0,100,25);
        // 准备验证码
        String str = "1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol0p1QAZ2WSX3EDC4RFV5TGB6YHN7UJM8IK9OL0P";
        // 准备循环获取验证码
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0;i < 4;i ++){
            char c = str.charAt(r.nextInt(str.length()));
            // 将字符拼接到sb上
            sb.append(c);
            // 输出字符到图片
            // 设置字体
            gh.setFont(new Font(null,Font.BOLD,18));
            // 设置颜色
            gh.setColor(new Color(50 + r.nextInt(150),50 + r.nextInt(150),50 + r.nextInt(150)));
            gh.drawString(c+"",(i * 25) + r.nextInt(5), 20 + r.nextInt(5));
        }
        // 添加干扰线
        gh.setColor(new Color(188,188,188));
        gh.drawLine(r.nextInt(100),r.nextInt(25),r.nextInt(100),r.nextInt(25));
        // 验证码sb
        // 通过客户端的标志将验证码存储到redis中。 key就是验证的标记
        redisTemplate.opsForValue().set(codeTag,sb.toString());
        redisTemplate.expire(codeTag,5, TimeUnit.MINUTES);
        // 将图片输出到输出流中
        ImageIO.write(bufferedImage,"JPEG",response.getOutputStream());
    }

}
